<template>
  <header class="header">
    <h1>todos</h1>
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="isAllDone"
    />
    <label for="toggle-all"></label>
    <input
      class="new-todo"
      placeholder="输入任务名称-回车确认"
      autofocus
      v-model.trim="content"
      @keyup.enter="handleSubmit"
    />
  </header>
</template>

<script lang="ts" setup>
// 计算全选状态，切换全选状态
import { defineProps, defineEmits, computed, ref } from '@vue/runtime-core'
import { Todo } from '@/types'

// 定义 Props 接收父组件传过来的数据
const props = defineProps<{ list: Todo[] }>()
// 定义 Emits 接收父组件的自定义事件
const emit = defineEmits<{(event: 'changeAll', value: boolean): void; (event: 'addTodo', value: string): void; }>()

// 计算全选状态
const isAllDone = computed<boolean>({
  get: () => props.list.length !== 0 && props.list.every((v) => v.done),
  set: (value: boolean) => emit('changeAll', value)
})

// 获取输入框数据
const content = ref('')
// 按回车键，新增待办任务
const handleSubmit = () => {
  // 非空判断
  if (!content.value) return alert('请输入内容~')
  // 调用添加
  emit('addTodo', content.value)
  // 添加后清空输入框
  content.value = ''
}
</script>
